<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

class PublicAction extends Action {
	// 检查用户是否登录

	protected function checkUser() {
		if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
			$this->assign('jumpUrl','Public/login');
			$this->error('没有登录');
		}
	}

	// 顶部页面
	public function top() {
		C('SHOW_RUN_TIME',false);			// 运行时间显示
		C('SHOW_PAGE_TRACE',false);
		$model	=	M("Group");
		$list	=	$model->where('status=1')->order('sort')->getField('id,title');
		$this->assign('nodeGroupList',$list);

        $configure = M('Configure');
        //提醒方式 0为声音提示，1为短信提示
        $alert_value = $configure->where('var_name = "alert_type" ')->getField('value');
        $this->assign("alert_value",$alert_value);
        if(isset ($_POST['alert_type'])){
            $configure->where('var_name = "alert_type" ')->setField('value',intval($_POST['alert_type'])) ;
            $this->assign('jumpUrl','__APP__/Public/main');
            $this->success("提醒方式修改成功！");
        }
		$this->display();
	}
	// 尾部页面
	public function footer() {
		C('SHOW_RUN_TIME',false);			// 运行时间显示
		C('SHOW_PAGE_TRACE',false);
		$this->display();
	}
	// 菜单页面
	public function menu() {
        $this->checkUser();
        if(isset($_SESSION[C('USER_AUTH_KEY')])) {
            //显示菜单项
            $menu  = array();
            if(isset($_SESSION['menu'.$_SESSION[C('USER_AUTH_KEY')]])) {

                //如果已经缓存，直接读取缓存
                $menu   =   $_SESSION['menu'.$_SESSION[C('USER_AUTH_KEY')]];
            }else {
                //读取数据库模块列表生成菜单项
                $node    =   M("Node");
				$id	=	$node->getField("id");
				$where['level']=2;
				$where['status']=1;
				$where['pid']=$id;
                $list	=	$node->where($where)->field('id,name,group_id,title')->order('sort asc')->select();
                $accessList = $_SESSION['_ACCESS_LIST'];
                foreach($list as $key=>$module) {
                     if(isset($accessList[strtoupper(APP_NAME)][strtoupper($module['name'])]) || $_SESSION['administrator']) {
                        //设置模块访问权限
                        $module['access'] =   1;
                        $menu[$key]  = $module;
                    }
                }
                //缓存菜单访问
                $_SESSION['menu'.$_SESSION[C('USER_AUTH_KEY')]]	=	$menu;
            }
            if(!empty($_GET['tag'])){
                $this->assign('menuTag',$_GET['tag']);
            }
			//dump($menu);
            $this->assign('menu',$menu);
		}
		C('SHOW_RUN_TIME',false);			// 运行时间显示
		C('SHOW_PAGE_TRACE',false);
		$this->display();
	}

    // 后台首页 查看系统信息
    public function main() {
        $configure = M('Configure');
        //提醒方式 0为声音提示，1为短信提示
        $alert_value = $configure->where('var_name = "alert_type" ')->getField('value');
        $this->assign("alert_value",$alert_value);

         C(include_once DATA_PATH.'~config.php');
         
         $curday = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
         $curday_night = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
         $msgmap = array(
             'approved' => 1, //后台未回复
             'status' => 0, //默认禁用状态
             'parent' => 0, //只列出前台客户的发言
             'user_id' => 0, //只列出前台客户的发言
         );
         $Comment = M('Comment');
         $Order = M('Order');
         $Checkin = M('Checkin');
         $Member = M('Member');
         $Landlord = M('Landlord');
         $Clean = M('Room_maintain');
         $count_msgs =$Comment ->where($msgmap)->count();
         $count_order = $Order->where('status = 1')->count();//状态为待确认的所有订单
         $count_checkin = $Checkin->where('start_time >='.$curday)->count();//统计今日入住的客户，以今日入住时间为准
         $count_live_checkin = A('Housestats')->countTodayCheckinRooms();//统计入住中的入住单
         $count_member = $Member->where('create_time >='.$curday." and type = 0")->count();//如果是今天且会员类型未被修改为其他类型的，则视为新会员
         $count_lesspay = $Checkin->where('status =2')->count();//余款未付

          $landlord_map = array(
             'alert_time' => array('between','1,'.time()),
         );
          $count_landlord = $Landlord->where($landlord_map)->count();//今日交租房东管理
          
         $leave_map = array(
             'alert_time' => array('between','1,'.time()),
         );
         $count_house = $Checkin->where($leave_map)->count();//按到期时间进行提醒，>=即提醒，止到用户删除或修改了这个提醒 时间

         $clean_map = array(//打扫提醒时间
             'alert_time' => array('between','1,'.time()),
             'type' =>0,//打扫的
         );
         $count_clean = $Clean->where($leave_map)->count();//按到期时间进行提醒，>=即提醒，止到用户删除或修改了这个提醒 时间
         
         $process_order_map = array(
             'status'=> array('between','2,4'),
             );//处理中的订单
        $count_process_order = $Order->where($process_order_map)->count();
        $count_today_free_rooms = count(getTodayFreeRooms());
        $count_to_check = $Checkin->where('status = 4')->count();//退款待结帐

        $this->assign('count_today_free_rooms',$count_today_free_rooms);//今日空房

        $this->assign('count_process_order',$count_process_order);//处理中的订单
        $this->assign('count_msgs',$count_msgs);
        $this->assign('count_order',$count_order);
        $this->assign('count_checkin',$count_checkin);
        $this->assign('count_member',$count_member);
        $this->assign('count_house',$count_house);
        $this->assign('count_lesspay',$count_lesspay);
        $this->assign('count_landlord',$count_landlord);
        $this->assign('count_live_checkin',$count_live_checkin);
        $this->assign('count_clean',$count_clean);
        $this ->assign('count_todo',M('Todo')->where('alert_time !=0 and user_id='.$_SESSION[C('USER_AUTH_KEY')])->count(id));
        $this ->assign('sumRentCost',(int)sumRentCost('', '', '', '',date('Y'), date('m')) );
        $this->assign('count_to_check',$count_to_check);
        /*
        $order = $Order ->where('status = 1')->findAll();
        $this->assign('orders',$order);
         $checkins = $Checkin ->where('start_time >='.$curday)->findAll();//以今日开始入住的时间为准
        $this->assign('checkins',$checkins);
        $this->assign('comments',$Comment->where($msgmap)->findAll());
        $this->assign('members',$Member->where('create_time >='.$curday." and type = 0")->findAll());
        $this->assign('leaves',$Checkin ->where($leave_map)->findAll());
         $this->assign('landlords',$Landlord ->where($landlord_map)->findAll());
        $this->assign('lesspay',$Checkin ->where('status=2')->findAll());//余款未付
        $this->assign('process_order',$Order ->where($process_order_map)->findAll());//处理中的订单
        $this->assign('clean',$Clean ->where($clean_map)->findAll());//需提醒的打扫记录
        */
        $this->display();
    }

	// 用户登录页面
	public function login() {
		if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
			$this->display();
		}else{
			$this->redirect('Index/index');
		}
	}

	public function index()
	{
		//如果通过认证跳转到首页
		redirect(__APP__);
	}

	// 用户登出
    public function logout()
    {
        if(isset($_SESSION[C('USER_AUTH_KEY')])) {
			unset($_SESSION[C('USER_AUTH_KEY')]);
			unset($_SESSION);
			session_destroy();
            $this->assign("jumpUrl",__URL__.'/login/');
            $this->success('登出成功！');
        }else {
            $this->error('已经登出！');
        }
    }

	// 登录检测
	public function checkLogin() {
		if(empty($_POST['account'])) {
			$this->error('帐号错误！');
		}elseif (empty($_POST['password'])){
			$this->error('密码必须！');
		}elseif (empty($_POST['verify'])){//验证码变为口令
			$this->error('口令必须！');
		}
        //生成认证条件
        $map            =   array();
		// 支持使用绑定帐号登录
		$map['account']	= $_POST['account'];
        $map["status"]	=	array('gt',0);
		if($verify = M('Configure')->where('var_name = "verify"')->getField('value') != $_POST['verify'] ) {
			$this->error("口令错误！");
		}
		import ( '@.ORG.RBAC' );
        $authInfo = RBAC::authenticate($map);
        //使用用户名、密码和状态的方式进行认证
        if(false === $authInfo) {
            $this->error('帐号不存在或已禁用！');
        }else {
            if($authInfo['password'] != md5($_POST['password'])) {
            	$this->error('密码错误！');
            }
            $_SESSION[C('USER_AUTH_KEY')]	=	$authInfo['id'];
            $_SESSION['email']	=	$authInfo['email'];
            $_SESSION['loginUserName']		=	$authInfo['nickname'];
            $_SESSION['lastLoginTime']		=	$authInfo['last_login_time'];
			$_SESSION['login_count']	=	$authInfo['login_count'];
            if($authInfo['account']=='admin') {
            	$_SESSION['administrator']		=	true;
            }
            //保存登录信息
			$User	=	M('User');
			$ip		=	get_client_ip();
			$time	=	time();
            $data = array();
			$data['id']	=	$authInfo['id'];
			$data['last_login_time']	=	$time;
			$data['login_count']	=	array('exp','login_count+1');
			$data['last_login_ip']	=	$ip;
			$User->save($data);

			// 缓存访问权限
            RBAC::saveAccessList();
			$this->success('登录成功！');

		}
	}
    // 更换密码
    public function changePwd()
    {
		$this->checkUser();
        //对表单提交处理进行处理或者增加非表单数据
		if(md5($_POST['verify'])	!= $_SESSION['verify']) {
			$this->error('验证码错误！');
		}
		$map	=	array();
        $map['password']= pwdHash($_POST['oldpassword']);
        if(isset($_POST['account'])) {
            $map['account']	 =	 $_POST['account'];
        }elseif(isset($_SESSION[C('USER_AUTH_KEY')])) {
            $map['id']		=	$_SESSION[C('USER_AUTH_KEY')];
        }
        //检查用户
        $User    =   M("User");
        if(!$User->where($map)->field('id')->find()) {
            $this->error('旧密码不符或者用户名错误！');
        }else {
			$User->password	=	pwdHash($_POST['password']);
			$User->save();
			$this->success('密码修改成功！');
         }
    }
public function profile() {
		$this->checkUser();
		$User	 =	 M("User");
		$vo	=	$User->getById($_SESSION[C('USER_AUTH_KEY')]);
		$this->assign('vo',$vo);
		$this->display();
	}
	 public function verify()
    {
		$type	 =	 isset($_GET['type'])?$_GET['type']:'gif';
        import("@.ORG.Image");
        Image::buildImageVerify(4,1,$type);
    }
// 修改资料
	public function change() {
		$this->checkUser();
		$User	 =	 D("User");
		if(!$User->create()) {
			$this->error($User->getError());
		}
		$result	=	$User->save();
		if(false !== $result) {
			$this->success('资料修改成功！');
		}else{
			$this->error('资料修改失败!');
		}
	}
}
?>